// index.js
const timer = require('../../utils/timer')
var rec = wx.getRecorderManager()
var temFilePath = null
var onStopCallBack = null
rec.onStop( res => {
  temFilePath = res.temFilePath
  console.log('录音成功：' + temFilePath)
  onStopCallBack && onStopCallBack(temFilePath)
})
var audioCtx = wx.createInnerAudioContext()
Page({
  data:{
    time:'00:00:00',
    state:0
  },
  rec: function() {
    switch(this.data.state){
      case 0:
        rec.start()
        timer.onTimeUpdate(time => {
          this.setData({ time })
        })
        timer.start()
        this.setData({ time: '00:00:00', state: 1})
        break
        case 1:
          rec.pause()
          timer.pause()
          this.setData({ state: 2 })
          break
          case 2:
          rec.pause()
          timer.pause()
          this.setData({ state: 1 })
          break
    }
  },
  stop: function() {
    rec.stop()
    timer.reset()
    this.setData({ state:0 })
  },
  play: function() {
    if(this.data.state > 0){
      onStopCallBack = temFilePath => {
        onStopCallBack = null
        audioCtx.src = temFilePath
        audioCtx.play()
        this.setData({ time:'播放录音' })
      }
      this.stop()
    }else if(temFilePath) {
      audioCtx.src = temFilePath
      audioCtx.play()
      this.setData({ time: '播放录音'})
    }else{
      this.setData({ time:'暂无录音'})
    }
  }
})
